package com.mirror.controller;

import com.mirror.entity.oldman.*;
import com.mirror.repository.*;
import com.mirror.util.CommonUtil;
import com.mirror.util.ResultUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.codec.digest.DigestUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Api(description = "护工管理")
@RestController
@RequestMapping("employees")
public class EmployeesController {


    @Autowired
    private EmployeesRepository employeesRepository;


    @ApiOperation(value = "班长列表", notes = "班长列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "data", value = "{}", required = true, dataType = "String"),
    })
    @PostMapping("/mlist")
    public Result mlist() {
        List<Employees> blist = employeesRepository.findAllByIsMonitorAndIsdel(true,false);
        return ResultUtil.success(blist);
    }

    @ApiOperation(value = "班长列表", notes = "班长列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "data", value = "{\"search\":\"搜索内容\"}", required = true, dataType = "String"),
    })
    @PostMapping("/showERFID")
    public Result showERFID(@RequestBody String data) {
        JSONArray ja = new JSONArray();
        JSONObject jo = new JSONObject();
        JSONObject tempData = new JSONObject(data);
        String search = tempData.optString("search");
        List<Employees> blist = employeesRepository.findAllByNameLikeOrNumLikeAndIsdel("%" + search + "%", "%" + search + "%",false);
        for (Employees e : blist) {
            JSONObject jo1 = new JSONObject();
            jo1.put("id", e.getId());
            jo1.put("eRFID", "caregivers:" + e.getId());
            ja.put(jo1);
        }
        jo.put("info", ja);
        return ResultUtil.success(jo.toString());
    }

    @ApiOperation(value = "护工列表无分页", notes = "护工列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "data", value = "{}", required = true, dataType = "String"),
    })
    @GetMapping("/allList")
    public Result allList() {
        List<Employees> blist = employeesRepository.findAllByIsdel(false);
        return ResultUtil.success(blist);
    }
    @ApiOperation(value = "护工列表无分页", notes = "护工列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "data", value = "{}", required = true, dataType = "String"),
    })
    @GetMapping("/houxuanList")
    public Result houxuanList() {
        List<Employees> blist = employeesRepository.findAllBySchProgramIsNull();
        return ResultUtil.success(blist);
    }

    @ApiOperation(value = "护工列表", notes = "护工列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "data", value = "{\"page\": \"页码\",\"size\": \"每页数量\",\"name\": \"姓名检索\"}", required = true, dataType = "String"),
    })
    @PostMapping("/pageList")
    public Result pageList(@RequestBody String data) throws ParseException {
        JSONObject tempData = new JSONObject(data);
        int page = tempData.getInt("page");
        int size = tempData.getInt("size");
        String name = tempData.optString("name");
        Sort sort = new Sort(Sort.Direction.DESC, "createDate");
        Pageable pageable = new PageRequest(page, size, sort);
        Page<Employees> atPage = null;
        if (CommonUtil.isNOT_Null(name)) {
            atPage = employeesRepository.findAllByNameLikeAndIsdel(pageable, "%" + name + "%",false);
        } else {
            atPage = employeesRepository.findAllByIsdel(pageable,false);
        }
        JSONArray ja = new JSONArray();
        for (Employees e : atPage) {
            ja.put(showEmployees(e));
        }
        JSONObject json = new JSONObject();
        json.put("memo", ja);
        json.put("totalPages", atPage.getTotalPages());
        json.put("totalElements", atPage.getTotalElements());
        return ResultUtil.success(json.toString());
    }

    public JSONObject showEmployees(Employees e) throws ParseException {
        JSONObject jo = new JSONObject();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        jo.put("id", e.getId());
        jo.put("enum", e.getNum());
        jo.put("name", e.getName());
        jo.put("address", e.getAddress());
        if (CommonUtil.isNOT_Null(e.getIdCard())) {
            String cardno = "";
            if (e.getIdCard().length() == 15) {
                cardno = CommonUtil.conver15CardTo18(e.getIdCard());
            } else {
                cardno = e.getIdCard();
            }
            String birthday = cardno.substring(6, 14);
            try {
                Date birthdate = new SimpleDateFormat("yyyyMMdd")
                        .parse(birthday);
                jo.put("age", CommonUtil.getAge(birthdate));
            } catch (ParseException e1) {
                e1.printStackTrace();
            }
        }
        jo.put("education", e.getEducation());
        jo.put("ethnic", e.getEthnic());
        jo.put("idCard", e.getIdCard());
        jo.put("idcardUrl", e.getIdcardUrl());
        jo.put("marriage", e.getMarriage());
        jo.put("sex", e.getSex());
        jo.put("isMonitor", e.getIsMonitor());
        jo.put("photoUrl", e.getPhotoUrl());
        jo.put("phone", e.getPhone());
        if(e.getSchProgram()!=null){
            jo.put("employeesGroupId",e.getSchProgram().getId());
            jo.put("employeesGroupName",e.getSchProgram().getName());
        }

        return jo;
    }


    @ApiOperation(value = "添加护工", notes = "添加护工")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "data", value = "{\"name\":\"姓名\",\"isMonitor\":\"是否是班长\",\"photoUrl\":\"照片路径\",\"address\":\"住址\",\"sex\":\"性别\",\"ethnic\":\"名族\",\"idCard\":\"身份证\",\"phone\":\"联系电话\",\"politicsStatus\":\"政治面貌\",\"education\":\"文化程度\",\"marriage\":\"婚姻\",\"contractUrl\":\"合同路径\",\"idcardUrl\":\"身份证路径\",\"contractB\":\"合同开始日期\",\"contractE\":\"合同结束日期\",\"position\":\"职务\",\"contractType\":\"合同类型\",\"hasTitle\":\"是否有职称\",\"titleUrl\":\"职称路径\"}", required = true, dataType = "String"),
    })
    @PostMapping("/save")
    public Result save(@RequestBody String data) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyMMddHHmmss");
        String num = sdf1.format(new Date());
        Employees e1 = employeesRepository.findAllByNumAndIsdel(num,false);
        if (e1 != null) {
            return ResultUtil.error(-1, "工号已重复");
        }
        JSONObject tempData = new JSONObject(data);
        String name = tempData.optString("name");
        String address = tempData.optString("address");
        String education = tempData.optString("education");
        String ethnic = tempData.optString("ethnic");
        boolean isMonitor = tempData.optBoolean("isMonitor");
        String contractType = tempData.optString("contractType");
        String contractUrl = tempData.optString("contractUrl");
        boolean hasTitle = tempData.optBoolean("hasTitle");
        String titleUrl = tempData.optString("titleUrl");
        String position = tempData.optString("position");
        String politicsStatus = tempData.optString("politicsStatus");
        String idCard = tempData.optString("idCard");
        String idcardUrl = tempData.optString("idcardUrl");
        String marriage = tempData.optString("marriage");
        String phone = tempData.optString("phone");
        String photoUrl = tempData.optString("photoUrl");
        String sex = tempData.optString("sex");
        Date contractB = null;
        Date contractE = null;
        if (CommonUtil.isNOT_Null(tempData.optString("contractB"))) {
            contractB = sdf.parse(tempData.optString("contractB"));
        }
        if (CommonUtil.isNOT_Null(tempData.optString("contractE"))) {
            contractE = sdf.parse(tempData.optString("contractE"));
        }


        Employees e = new Employees();
        e.setIsdel(false);
        e.setNum(num);
        e.setPassword("123456");
        e.setMd5pass(DigestUtils.md5Hex("123456"));
        e.setIsMonitor(isMonitor);
        e.setName(name);
        e.setCreateDate(new Date());
        e.setAddress(address);
        e.setContractB(contractB);
        e.setContractE(contractE);
        e.setContractType(contractType);
        e.setContractUrl(contractUrl);
        e.setEducation(education);
        e.setEthnic(ethnic);
        e.setHasTitle(hasTitle);
        e.setIdCard(idCard);
        e.setIdcardUrl(idcardUrl);
        e.setMarriage(marriage);
        e.setPhone(phone);
        e.setPhotoUrl(photoUrl);
        e.setPoliticsStatus(politicsStatus);
        e.setPosition(position);
        e.setSex(sex);
        e.setTitleUrl(titleUrl);
        return ResultUtil.success(employeesRepository.save(e));
    }

    @ApiOperation(value = "修改护工", notes = "修改护工")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "data", value = "{\"id\":\"员工id\",\"name\":\"姓名\",\"isMonitor\":\"是否是班长\",\"photoUrl\":\"照片路径\",\"address\":\"住址\",\"sex\":\"性别\",\"ethnic\":\"名族\",\"idCard\":\"身份证\",\"phone\":\"联系电话\",\"politicsStatus\":\"政治面貌\",\"education\":\"文化程度\",\"marriage\":\"婚姻\",\"contractUrl\":\"合同路径\",\"idcardUrl\":\"身份证路径\",\"contractB\":\"合同开始日期\",\"contractE\":\"合同结束日期\",\"position\":\"职务\",\"contractType\":\"合同类型\",\"hasTitle\":\"是否有职称\",\"titleUrl\":\"职称路径\"}", required = true, dataType = "String"),
    })
    @PostMapping("/edit")
    public Result edit(@RequestBody String data) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        JSONObject tempData = new JSONObject(data);
        String id = tempData.optString("id");
        String name = tempData.optString("name");
        String address = tempData.optString("address");
        String education = tempData.optString("education");
        String ethnic = tempData.optString("ethnic");
        boolean isMonitor = tempData.getBoolean("isMonitor");
        String contractType = tempData.optString("contractType");
        String contractUrl = tempData.optString("contractUrl");
        boolean hasTitle = tempData.optBoolean("hasTitle");
        String titleUrl = tempData.optString("titleUrl");
        String position = tempData.optString("position");
        String politicsStatus = tempData.optString("politicsStatus");
        String idCard = tempData.optString("idCard");
        String idcardUrl = tempData.optString("idcardUrl");
        String marriage = tempData.optString("marriage");
        String phone = tempData.optString("phone");
        String photoUrl = tempData.optString("photoUrl");
        String sex = tempData.optString("sex");
        Date contractB = null;
        Date contractE = null;
        if (CommonUtil.isNOT_Null(tempData.optString("contractB"))) {
            contractB = sdf.parse(tempData.optString("contractB"));
        }
        if (CommonUtil.isNOT_Null(tempData.optString("contractE"))) {
            contractE = sdf.parse(tempData.optString("contractE"));
        }
        Employees e = employeesRepository.findOne(id);
        if (e == null) {
            return ResultUtil.error(-1, "获取员工失败");
        }
        e.setIsMonitor(isMonitor);
        e.setName(name);
        e.setCreateDate(new Date());
        e.setAddress(address);
        e.setContractB(contractB);
        e.setContractE(contractE);
        e.setContractType(contractType);
        e.setContractUrl(contractUrl);
        e.setEducation(education);
        e.setEthnic(ethnic);
        e.setHasTitle(hasTitle);
        e.setIdCard(idCard);
        e.setIdcardUrl(idcardUrl);
        e.setMarriage(marriage);
        e.setPhone(phone);
        e.setPhotoUrl(photoUrl);
        e.setPoliticsStatus(politicsStatus);
        e.setPosition(position);
        e.setSex(sex);
        e.setTitleUrl(titleUrl);
        return ResultUtil.success(employeesRepository.save(e));
    }

    @ApiOperation(value = "删除护工", notes = "删除护工")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "data", value = "{\"id\":\"员工id\"}", required = true, dataType = "String"),
    })
    @PostMapping("/del")
    public Result del(@RequestBody String data) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        JSONObject tempData = new JSONObject(data);
        String id = tempData.optString("id");
        Employees e = employeesRepository.findOne(id);
        if (e == null) {
            return ResultUtil.error(-1, "获取员工失败");
        }
       e.setIsdel(true);
        return ResultUtil.success(employeesRepository.save(e));
    }

    @ApiOperation(value = "护工登录", notes = "护工登录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "data", value = "{\"Enum\":\"工号\",\"password\":\"密码\",\"RFID\":\"rfid\"}", required = true, dataType = "String"),
    })
    @PostMapping("/login")
    public Result login(@RequestBody String data) throws ParseException {
        JSONObject tempData = new JSONObject(data);
        String Enum = tempData.optString("Enum");
        String password = tempData.optString("password");
        String RFID = tempData.optString("RFID");

        Employees e = null;
        if (CommonUtil.isNOT_Null(RFID)) {
            if (RFID.split(":").length == 1
                    || (!"doctor".equals(RFID.split(":")[0])
                    && !"caregivers".equals(RFID.split(":")[0]))) {
                return ResultUtil.error(-1, "标签错误");
            }
            String id = RFID.split(":")[1];
            e = employeesRepository.findOne(id);
            if (e == null) {
                return ResultUtil.error(-1, "获取员工失败");
            }
        } else {
            e = employeesRepository.findAllByPhone(Enum);
            if (e == null || !e.getPassword().equals(password)) {
                return ResultUtil.error(-1, "工号或密码错误!");
            }
        }

        return ResultUtil.success(showEmployees(e).toString());
    }

}

